//
//  CYFinanceDetailViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/4.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYFinanceDetailViewController.h"

#import "CYFinanceDetailViewModel.h"

#import "CYProfitsCalculatorView.h"
#import "CYEvaluateView.h"

#import "CYFinanceDetailInfoCell.h"
#import "CYFinanceDetailActionCell.h"
#import "CYEmptyCell.h"

#import "CYFinanceMemberViewController.h"
#import "CYFinanceInvestViewController.h"
#import "CYMainController.h"
#import "CYWebViewController.h"
#import "CYFinanceInfoViewController.h"

#import "CYGlobalTimerManager.h"



@interface CYFinanceDetailViewController ()

@property(nonatomic, strong)CYFinanceDetailViewModel *viewModel;
@property(nonatomic, assign)CYFinanceDetailStatus status;

@property(nonatomic, strong)CYFinanceDetailInfoCellObject *infoCell;
@property(nonatomic, strong)CYFinanceDetailActionCellObject *targetCell;
@property(nonatomic, strong)CYFinanceDetailActionCellObject *riskControlCell;
@property(nonatomic, strong)CYFinanceDetailActionCellObject *cardLimitCell;
@property(nonatomic, strong)CYFinanceDetailActionCellObject *memberCountCell;
@property(nonatomic, strong)CYFinanceDetailActionCellObject *qaCell;

@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UIButton *tryButton;
@property(nonatomic, strong)UIButton *statusButton;
@property(nonatomic, strong)UIView *bottomLine;

@property(nonatomic, assign)BOOL loading;
@property(nonatomic, assign)BOOL evaluated;

@property(nonatomic, strong)NSString *hint;

@end


@implementation CYFinanceDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)loadUI
{
    self.bottomView = [[UIView alloc] init];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.bottomView];
    {
        self.bottomLine = [UIView cy_lineWithColor:HEXCOLOR(@"f6f6f6")];
        [self.bottomView addSubview:self.bottomLine];
        
        self.tryButton = [[UIButton alloc] init];
        [self.tryButton setImage:(SCREEN_HEIGHT == 812.0) ? CYImage(@"finance_detail_try_x") : CYImage(@"finance_detail_try") forState:UIControlStateNormal];
        [self.tryButton addTarget:self action:@selector(onTryButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.tryButton];
        
        self.statusButton = [[UIButton alloc] init];
        [self.statusButton setTitleColor:HEXCOLOR(@"FFFFFF") forState:UIControlStateNormal];
        [self.statusButton setTitleColor:HEXCOLOR(@"FFFFFF") forState:UIControlStateDisabled];
        self.statusButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
        [self.statusButton addTarget:self action:@selector(onStatusButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:self.statusButton];
    }
}

- (void)loadData
{
    @weakify(self);
    
    [self refreshStatusButton];
    [CYStandardGlobalTimerManager addTarget:self withBlock:^{
        @strongify(self);
        [self refreshStatusButton];
    }];
    
    NSMutableArray *cells = [[NSMutableArray alloc] init];
    {
        self.infoCell = [CYFinanceDetailInfoCellObject objectWithCellClass:[CYFinanceDetailInfoCell class]];
        [cells addObject:self.infoCell];
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        self.targetCell = [CYFinanceDetailActionCellObject objectWithCellClass:[CYFinanceDetailActionCell class]];
        self.targetCell.title = @"项目介绍";
        [cells addObject:self.targetCell];
    }
    {
        self.riskControlCell = [CYFinanceDetailActionCellObject objectWithCellClass:[CYFinanceDetailActionCell class]];
        self.riskControlCell.title = @"安全保障";
        [cells addObject:self.riskControlCell];
    }
    {
        self.cardLimitCell = [CYFinanceDetailActionCellObject objectWithCellClass:[CYFinanceDetailActionCell class]];
        self.cardLimitCell.title = @"充值限额";
        [cells addObject:self.cardLimitCell];
    }
    {
        self.memberCountCell = [CYFinanceDetailActionCellObject objectWithCellClass:[CYFinanceDetailActionCell class]];
        self.memberCountCell.title = @"投资记录";
        [cells addObject:self.memberCountCell];
    }
    {
        self.qaCell = [CYFinanceDetailActionCellObject objectWithCellClass:[CYFinanceDetailActionCell class]];
        self.qaCell.title = @"常见问题";
        self.qaCell.isBottom = YES;
        [cells addObject:self.qaCell];
    }
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
    self.tableView.dataSource = self.tableModel;
    [self.tableView reloadData];
}

- (void)layoutUI
{
    self.bottomView.width = self.contentView.width;
    self.bottomView.height = SAFE_BOTTOM_HEIGHT;
    self.bottomView.left = 0;
    self.bottomView.bottom = self.contentView.height;
    {
        self.bottomLine.width = self.bottomView.width;
        self.bottomLine.height = 1 / SCREEN_SCALE;
        self.bottomLine.left = 0;
        self.bottomLine.bottom = 0;
        
        self.tryButton.width = self.bottomView.height;
        self.tryButton.height = self.bottomView.height;
        self.tryButton.left = 0;
        self.tryButton.top = 0;
        
        self.statusButton.width = self.bottomView.width - self.tryButton.right;
        self.statusButton.height = self.bottomView.height;
        self.statusButton.left = self.tryButton.right;
        self.statusButton.top = 0;
    }
    
    self.tableView.width = self.contentView.width;
    self.tableView.height = self.bottomView.top;
    self.tableView.left = 0;
    self.tableView.top = 0;
}

- (void)loadDataFromServer
{
    if(self.loading)
    {
        return;
    }
    self.loading = YES;
    @weakify(self);
    [CYStandardDataAPI project_detailWithID:self.fid complete:^(CYResponse *response) {
        @strongify(self);
        
        self.hint = nil;
        
        if(response.code == 0)
        {
            CYDataAPIFinanceModel *apiModel = [CYDataAPIFinanceModel mj_objectWithKeyValues:response.content];
            self.viewModel = [CYFinanceDetailViewModel modelWithAPIModel:apiModel];
            self.infoCell.model = self.viewModel;
            self.memberCountCell.subtitle = [self.viewModel.memberCount stringByAppendingString:@"已投资"];
            self.targetCell.tag = self.viewModel.tag;
            if([apiModel.prompt isKindOfClass:[NSString class]] && apiModel.prompt.length)
            {
                self.hint = apiModel.prompt;
            }
            [self.tableView reloadData];
            self.navigationItem.title = self.viewModel.title;

            [self refreshStatusButton];
        }
        else
        {
            if(self.viewModel == nil)
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
            [self.tableView reloadData];
        }
        self.loading = NO;
    }];
    
    [CYStandardDataAPI riskEvaluate_getRiskByTokenWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            if(response.content)
            {
                self.evaluated = YES;
                return;
            }
        }
        self.evaluated = NO;
    }];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

- (void)close
{
    [MobClick event:UM_EVENT_0022];
    [super close];
}

#pragma mark - Actions
- (void)showMembersAction
{
    CYFinanceMemberViewController *financeMemberViewController = [[CYFinanceMemberViewController alloc] init];
    financeMemberViewController.fid = self.fid;
    [self.navigationController pushViewController:financeMemberViewController animated:YES];
}

- (void)investAction
{
    if(self.evaluated)
    {
        if(SAFE_NUMBER(self.viewModel.apiModel.notCanBuy).integerValue != 0)
        {
            [SVProgressHUD showInfoWithStatus:SAFE_STRING(self.viewModel.apiModel.notCanBuyDesc)];
        }
        else
        {
            CYFinanceInvestViewController *financeInvestViewController = [[CYFinanceInvestViewController alloc] init];
            financeInvestViewController.fid = self.fid;
            [self.navigationController pushViewController:financeInvestViewController animated:YES];
        }
    }
    else
    {
        @weakify(self);
        CYEvaluateView *view = [[CYEvaluateView alloc] init];
        view.evaluateAction = ^{
            @strongify(self);
            CYWebViewController *webViewController = [[CYWebViewController alloc] init];
            webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/risk_exam.html?from=1"];
            [self.navigationController pushViewController:webViewController animated:YES];
        };
        [view show];
    }
}

- (void)showLogInAction
{
    [[CYMainController standardController] showLogIn];
}

- (void)safeguardsAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/safe.html"];
    webViewController.defaultTitle = @"四重保障";
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)targetAction
{
    CYFinanceInfoViewController *webViewController = [[CYFinanceInfoViewController alloc] init];
    webViewController.fid = self.fid;
    webViewController.url = [NSString stringWithFormat:@"%@%@%@", CY_H5_BASE_URL, @"views/introduce_bd.html?id=", SAFE_NUMBER(self.fid).stringValue];
    webViewController.defaultTitle = @"项目介绍";
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)cardLimitAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/bank_info.html"];
    webViewController.defaultTitle = @"限额说明";
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)qaAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/common_problem.html"];
    webViewController.defaultTitle = @"常见问题";
    [self.navigationController pushViewController:webViewController animated:YES];
}

#pragma mark - Control Events
- (void)onTryButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0027];
    if(self.viewModel)
    {
        CYProfitsCalculatorView *view = [[CYProfitsCalculatorView alloc] init];
        view.rate = @(SAFE_NUMBER(self.viewModel.apiModel.userInterest).doubleValue / 100 + SAFE_NUMBER(self.viewModel.apiModel.extraInterest).doubleValue / 100);
        view.due = SAFE_NUMBER(self.viewModel.apiModel.duration);
        [view reloadInfos];
        [view show];
    }
}

- (void)onStatusButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0028];
    switch(self.status)
    {
        case CYFinanceDetailStatusNormal:
        {
            [self investAction];
            break;
        }
        case CYFinanceDetailStatusDisable:
        {
            break;
        }
        case CYFinanceDetailStatusNotLoggedIn:
        {
            [self showLogInAction];
            break;
        }
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.memberCountCell)
    {
        [MobClick event:UM_EVENT_0026];
        [self showMembersAction];
        return;
    }
    if(cellObject == self.riskControlCell)
    {
        [MobClick event:UM_EVENT_0024];
        [self safeguardsAction];
        return;
    }
    if(cellObject == self.cardLimitCell)
    {
        [MobClick event:UM_EVENT_0025];
        [self cardLimitAction];
        return;
    }
    if(cellObject == self.targetCell)
    {
        [MobClick event:UM_EVENT_0023];
        [self targetAction];
        return;
    }
    if(cellObject == self.qaCell)
    {
        [self qaAction];
        return;
    }
}

#pragma mark - Private Method
- (void)refreshStatusButton
{
    if(CYStandardAuthManager.currentAuth)
    {
        if(self.viewModel)
        {
            switch(self.viewModel.status)
            {
                case CYFinanceViewModelStatusWillSale:
                {
                    NSTimeInterval timeInterval = [self.viewModel.saleDate timeIntervalSinceNow];
                    if(timeInterval < 0)
                    {
                        self.status = CYFinanceDetailStatusNormal;
                        self.statusButton.enabled = YES;
                        [self.statusButton setBackgroundImage:[UIImage imageWithColor:APP_DEFAULT_COLOR_RED size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
                        [self.statusButton setTitle:@"立即投资" forState:UIControlStateNormal];
                    }
                    else
                    {
                        self.status = CYFinanceDetailStatusDisable;
                        self.statusButton.enabled = NO;
                        [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"FFC4C8") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
                        [self.statusButton setTitle:[NSString stringWithFormat:@"%@后开售", self.viewModel.saleDate.cy_financeCountDown] forState:UIControlStateNormal];
                    }
                    break;
                }
                case CYFinanceViewModelStatusOnSale:
                {
                    self.status = CYFinanceDetailStatusNormal;
                    self.statusButton.enabled = YES;
                    [self.statusButton setBackgroundImage:[UIImage imageWithColor:APP_DEFAULT_COLOR_RED size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
                    [self.statusButton setTitle:@"立即投资" forState:UIControlStateNormal];
                    break;
                }
                case CYFinanceViewModelStatusFull:
                {
                    self.status = CYFinanceDetailStatusDisable;
                    self.statusButton.enabled = NO;
                    [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"CCCCCC") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
                    [self.statusButton setTitle:@"已售罄" forState:UIControlStateNormal];
                    break;
                }
                case CYFinanceViewModelStatusDone:
                {
                    self.status = CYFinanceDetailStatusDisable;
                    self.statusButton.enabled = NO;
                    [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"CCCCCC") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
                    [self.statusButton setTitle:@"已还款" forState:UIControlStateNormal];
                    break;
                }
            }
        }
        else
        {
            self.status = CYFinanceDetailStatusDisable;
            self.statusButton.enabled = NO;
            [self.statusButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"CCCCCC") size:CGSizeMake(1, 1)] forState:UIControlStateDisabled];
            [self.statusButton setTitle:@"正在获取数据" forState:UIControlStateNormal];
        }
    }
    else
    {
        self.status = CYFinanceDetailStatusNotLoggedIn;
        self.statusButton.enabled = YES;
        [self.statusButton setBackgroundImage:[UIImage imageWithColor:APP_DEFAULT_COLOR_RED size:CGSizeMake(1, 1)] forState:UIControlStateNormal];
        [self.statusButton setTitle:@"登录" forState:UIControlStateNormal];
    }
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    if(self.hint)
    {
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
        label.numberOfLines = 0;
        label.text = self.hint;
        label.textColor = HEXCOLOR(@"EFA839");
        label.size = [label sizeThatFits:CGSizeMake(SCREEN_WIDTH - 64, MAXFRAG)];
        view.width = SCREEN_WIDTH;
        view.height = MAX(40, label.height + 27);
        view.backgroundColor = HEXCOLOR(@"FFFBEA");
        label.centerY = view.height / 2;
        label.left = 41;
        [view addSubview:label];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:CYImage(@"ico_prompt_info_yellow")];
        imageView.left = 20;
        imageView.top = label.top;
        [view addSubview:imageView];
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(self.hint)
    {
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
        label.numberOfLines = 0;
        label.text = self.hint;
        return MAX(40, [label sizeThatFits:CGSizeMake(SCREEN_WIDTH - 64, MAXFRAG)].height + 27);
    }
    else
    {
        return 0;
    }
}

@end
